#!/bin/bash

# 检查端口占用
check_and_kill_port() {
    local port=$1
    if lsof -i :$port > /dev/null 2>&1; then
        echo "Port $port is in use. Waiting 3 seconds before killing the process..."
        sleep 3
        lsof -ti :$port | xargs kill -9
        echo "Process using port $port has been terminated."
    fi
}

# 检查前端和后端端口
check_and_kill_port 3003
check_and_kill_port 5063

# 安装后端依赖
echo "Installing backend dependencies..."
pip install -r requirements.txt

# 进入前端目录
cd frontend

# 安装前端依赖
echo "Installing frontend dependencies..."
npm install

# 返回根目录
cd ..

# 启动后端服务
echo "Starting backend server..."
python3 main.py &

# 等待后端服务启动
sleep 8

# 验证后端服务是否正常运行
echo "Verifying backend service..."
if curl -s http://127.0.0.1:5063/api/prompts > /dev/null; then
    echo "Backend service is running correctly."
else
    echo "Backend service is not responding. Please check logs."
    exit 1
fi

# 进入前端目录并启动前端服务
cd frontend
echo "Starting frontend server..."
npm run dev &

# 等待前端服务启动
sleep 5

# 返回根目录
cd ..

echo "服务已启动："
echo "后端服务：http://localhost:5063"
echo "前端服务：http://localhost:3003"
echo "请打开浏览器访问前端地址"